package com.jfl.utils;

import java.util.Map;
import java.util.UUID;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.codec.Base64;

import com.google.common.collect.Maps;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;

/**
 * token工具类
 * 
 * @author 赵炎
 * @version [V1.00, 2019年7月17日]
 * @since V1.00
 */
public class JwtUtil
{
    /**
     * 获取token
     * 
     * @param claimMap
     * @param encryKey
     * @param secondTimeOut
     * @return
     */
    public static String createJWT(String id, String encryKey, int secondTimeOut)
    {
        return Jwts.builder()
            .setId(UUID.randomUUID().toString()) // Id
            
            .setSubject("jfl") // 主题
            .setIssuer("yxxmg") // 签发者
            .setIssuedAt(DateUtil.getCurrentDate()) // 签发日期
            
            .setAudience("custom")
            .compressWith(CompressionCodecs.GZIP)
            .signWith(SignatureAlgorithm.HS256, generateKey()) // 签名算法及秘钥
            .setExpiration(DateUtils.addMilliseconds(DateUtil.getCurrentDate(), secondTimeOut))
            // .addClaims(claimMap)
            .compact();
    }
    
    public static SecretKey generateKey()
    {
        byte[] encodeKey = Base64.decode("8677df7fc3a34e26a61c034d5ec8245d");
        SecretKey secretKey = new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES");
        return secretKey;
    }
    
    public static Claims validateJWT(String jwt)
    {
        Claims claims = null;
        try
        {
            claims = parseJWT(jwt);
        }
        catch (ExpiredJwtException e)
        {
        }
        catch (SignatureException e)
        {
        }
        catch (Exception e)
        {
        }
        return claims;
    }
    
    /**
     * 
     * 解析JWT字符串
     * 
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt)
        throws Exception
    {
        SecretKey secretKey = generateKey();
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
    }
    
    public static void main(String[] args) throws InterruptedException
    {
       String sc = createJWT("1", "张三", 4000);
       System.out.println(sc);
       System.out.println(validateJWT(sc));
       Thread.sleep(3000);
       System.out.println(validateJWT(sc));
       Thread.sleep(1000);
       System.out.println(validateJWT(sc));
    }
}
